﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net.Mail;
using System.Runtime.Remoting.Messaging;
using System.Threading;
using System.Web;
using System.Web.Mail;
using Calendar.Logic.Log;
using Calendar.Logic.ObjectManager;
using Calendar.Logic.ObjectModel;
using MailMessage = System.Net.Mail.MailMessage;

namespace Calendar.Web.Core
{
    public static class EmailSchedules
    {

        static private Thread _dispatch = null;

        static EmailSchedules()
        {
            _dispatch = new Thread(Run);
        }

        static public void Start()
        {
            if (!_dispatch.IsAlive) _dispatch.Start();
        }

        static public void End()
        {
            if (_dispatch.IsAlive) _dispatch.Abort();
        }

        static private void Run()
        {
            var jss = new System.Web.Script.Serialization.JavaScriptSerializer();

            while (_dispatch.IsAlive)
            {
                List<Email> emails = EmailManager.Instance.SelectNotSent();
                foreach (var email in emails)
                {
                    try
                    {
                        if (email == null || email.ID == 0) break;

                        dynamic emailToSend = new Postal.Email(email.Template);
                        emailToSend.To = email.To;
                        if (!string.IsNullOrEmpty(email.Params)) emailToSend.Params = jss.Deserialize<Dictionary<string, string>>(email.Params);

                        if (!string.IsNullOrEmpty(email.Attach))
                        {
                            var attach = jss.Deserialize<List<int>>(email.Attach);
                            foreach (var fileId in attach)
                            {
                                //var file = FileManager.Instance.SelectById(fileId);
                                //if (file.FileStream != null)
                                //{
                                //    emailToSend.Attach(new Attachment(file.FileStream, file.Name, file.ContentType));
                                //}
                                //else
                                //{
                                //    LogManager.Log(DsLogLevel.WARNING, "Отправка Email-оповещения", "Не удалось найти файл ID = {0}", fileId);
                                //}
                            }
                        }

                        emailToSend.Send();
                        EmailManager.Instance.Sent(email.ID);
                    }
                    catch (SmtpException exc)
                    {
                        LogManager.Log(DsLogLevel.ERROR, "Отправка Email-оповещения", "Ошибка при отправке: {0}",
                            exc.Message + (email != null ? "Id = " + email.ID : ""));
                    }
                    catch (Exception exc)
                    {
                        LogManager.Log(DsLogLevel.ERROR, "Отправка Email-оповещения", "Ошибка при отправке: {0}",
                            exc.Message + (email != null ? "Id = " + email.ID : ""));
                    }
                }

                Thread.Sleep(60000);
            }
        }

    }
}